package com.hhs.storage.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.hhs.storage.bean.*;
import com.hhs.storage.dao.TopicMessageDao;
import com.hhs.storage.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hhs.storage.util.StringUtil;
import com.hhs.storage.util.SysUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author hhs
 * @since 2023-03-01
 */
@Service
@Transactional
public class TopicMessageServiceImpl extends ServiceImpl<TopicMessageDao, TopicMessage> implements TopicMessageService {
    @Resource
    private BaseUserService userService;
    @Resource
    private HttpServletRequest request;
    @Resource
    private ProjectPlanService projectPlanService;
    @Resource
    private PersonalPlanService personalPlanService;
    @Resource
    private LeaderTaskService leaderTaskService;
    @Resource
    private TopicUserRefuseCountService topicUserRefuseCountService;
    @Resource
    ProjectMemberService projectMemberService;
    @Override
    public Map<String, Object> getListByTopicId(String topicId,String bakTopicId,Boolean lookAll,String clickItemIds) {
        //针对的讨论对象id必须
        QueryWrapper<TopicMessage> queryWrapper = new QueryWrapper<>();
        if(!StringUtil.iszNull(topicId)){
            queryWrapper.eq("topic_id", topicId);
        }
        if(!StringUtil.iszNull(clickItemIds)){
            queryWrapper.in("user_id", Arrays.asList(clickItemIds.split(",")));
        }

        if(!StringUtil.iszNull(bakTopicId)){
            queryWrapper.eq("bak_topic_id", bakTopicId);
            if(StringUtil.iszNull(topicId)){
                String loginUserId = SysUtil.getLoginUserId(request);
                if(lookAll==null||lookAll==false)
                queryWrapper.and(wrapper -> wrapper.eq("user_id",loginUserId).or().eq("reply_user_id",loginUserId));
            }
        }
        queryWrapper.orderByAsc("create_time");//默认升序
        List<TopicMessage> list = this.list(queryWrapper);
        List<TopicMessage> rows = new ArrayList<>();
        //所有最顶级评论
        for (int i = 0; i < list.size(); i++) {
            TopicMessage topicMessage = list.get(i);
            if (StringUtils.isEmpty(topicMessage.getTopId())) {//顶级评论是空
                BaseUser user = userService.getById(topicMessage.getUserId());
                topicMessage.setUser(user);
                if(StringUtils.isNotEmpty(bakTopicId)) {
                    BaseUser replyUser = userService.getById(topicMessage.getReplyUserId());
                    topicMessage.setReplyUser(replyUser);
                }
                rows.add(topicMessage);
            }
        }
        //查找所有顶级评论的子评论
        for (int i = 0; i < rows.size(); i++) {
            TopicMessage top = rows.get(i);
            for (int j = 0; j < list.size(); j++) {
                TopicMessage child = list.get(j);
                if (top.getId().equals(child.getTopId())) {
                    BaseUser user = userService.getById(child.getUserId());
                    child.setUser(user);
                    BaseUser replyUser = userService.getById(child.getReplyUserId());
                    child.setReplyUser(replyUser);
                    top.getReplyList().add(child);
                }
            }
        }
        //按时间逆序排序
        rows.sort(new Comparator<TopicMessage>() {
            @Override
            public int compare(TopicMessage o1, TopicMessage o2) {
                return o2.getCreateTime().compareTo(o1.getCreateTime());
            }
        });
        //将当前用户当前话题的数据设置已读
        readMessage(topicId);

        Map map = new HashMap();
        map.put("code", 1);
        map.put("rows", rows);
        return map;
    }

    /**
     * 查询当前用户消息分组列表
     *
     * @param param
     * @return
     */
    @Override
    public Map<String, Object> getMessageGroupList(InputParam param) {
        String userId = SysUtil.getLoginUserId(request);
        List<TopicMessage> list = this.baseMapper.getMessageGroupList(userId, param);
        for (int i = 0; i < list.size(); i++) {
            TopicMessage message = list.get(i);
            //查询相应话题数据
            setTopicTitle(message);
            QueryWrapper<TopicMessage> qw = new QueryWrapper();
            qw.eq("reply_user_id", userId);//回复的用户id
            qw.eq("topic_id", message.getTopicId());//话题id
            qw.eq("is_read", TopicMessage.UNREAD);//查询未读
            int total = this.count(qw);
            message.getTopicMap().put("unreadNum", total);//未读数据个数
        }

        Long total = this.baseMapper.getMessageGroupTotal(userId);

        Map map = new HashMap();
        map.put("code", 1);
        map.put("rows", list);
        map.put("total", total);
        return map;
    }

    /**
     * 设置消息标题，内容
     * @param message
     */
    public void setTopicTitle(TopicMessage message) {
        String loginUserId=SysUtil.getLoginUserId(request);
        //个人计划
        if (message.getType() == TopicMessage.TYPE_PERSONAL) {
            PersonalPlan topic = personalPlanService.getById(message.getTopicId());
            if (topic != null) {
                BaseUser sender=userService.getById(message.getUserId());//消息发送者
                if (sender.getId().equals(SysUtil.getLoginUserId(request))){
                    sender.setName("我");
                }

                BaseUser receiver=userService.getById(message.getReplyUserId());//消息接收者
                if (receiver.getId().equals(SysUtil.getLoginUserId(request))){
                    receiver.setName("我");
                }
                DateTimeFormatter formatter=DateTimeFormatter.ofPattern("yyyy-MM-dd");
                DateTimeFormatter formatter2=DateTimeFormatter.ofPattern("HH:mm");
                String title=sender.getName()+" 针对 "+formatter.format(topic.getWorkDate())+" "+
                        formatter2.format(topic.getStartTime())+"-"
                        +formatter2.format(topic.getEndTime())+
                        " "+topic.getTitle()+" 给 "+receiver.getName()+" 的留言";
                message.getTopicMap().put("title", title);

                message.getTopicMap().put("content", topic.getContent());
            }
        }
        //项目计划
        if (message.getType() == TopicMessage.TYPE_PROJECT) {
            ProjectPlan topic = projectPlanService.getById(message.getTopicId());
            if (topic != null) {
                message.getTopicMap().put("title", "针对 "+topic.getName()+" 的留言");
                message.getTopicMap().put("content", topic.getContent());
            }
        }
        //上级留言
        if (message.getType() == TopicMessage.TYPE_LEADER) {
            String topic = message.getTopicId();
            String[] ids = topic.split("-");//规格 领导id-下属id
            BaseUser leader = userService.getById(ids[0]);
            BaseUser baseuser = userService.getById(ids[1]);
            if(SysUtil.getLoginUserId(request).equals(baseuser.getId())){
                //发送人是下属
                message.getTopicMap().put("title", "给 " + leader.getName() + " 留言");

            }else{
                //发送人是领导
                message.getTopicMap().put("title", baseuser.getName() + " 给我的留言");
            }
            message.getTopicMap().put("content", null);
        }
        //项目通知
        if (message.getType() == TopicMessage.TYPE_PROJECT_GROUP) {
            message.getTopicMap().put("title", "系统通知");
            message.getTopicMap().put("content", message.getContent());
        }
        //项目领导任务
        if (message.getType() == TopicMessage.TYPE_LEADER_TASK) {
            LeaderTask task=leaderTaskService.getById(message.getTopicId());
            if (task!=null){
                String leaderId=task.getLeaderId();
                String userId=task.getUserId();
                BaseUser leader=userService.getById(leaderId);
                BaseUser user=userService.getById(userId);
                StringBuffer title=new StringBuffer();
                if(loginUserId.equals(message.getUserId())){
                    //当前用户是发送人
                    if (leaderId.equals(loginUserId)){
                        //消息发送人是领导
                        title.append("我针对 ");
                        title.append(task.getTitle() +" 给下属-"+user.getName()+" 的留言");
                    }else if(userId.equals(loginUserId)){
                        //消息发送人是下属
                        title.append("我针对 ");
                        title.append(task.getTitle() +" 给领导-"+leader.getName()+" 的留言");
                    }
                }
                if(loginUserId.equals(message.getReplyUserId())){
                    //当前用户是接收人
                    if (leaderId.equals(loginUserId)){
                        //消息接收人是领导
                        title.append("下属-"+user.getName()+" 针对 ");
                        title.append(task.getTitle() +" 给我的留言");
                    }else if(userId.equals(loginUserId)){
                        //消息接收人是下属
                        title.append("领导-"+leader.getName()+" 针对 ");
                        title.append(task.getTitle() +" 给我的留言");
                    }
                }
                message.getTopicMap().put("title", title.toString());
                message.getTopicMap().put("content", task.getContent());
            }

        }
    }

    @Override
    public Map<String, Object> checkHasNewMessage() {
        QueryWrapper<TopicMessage> qw = new QueryWrapper();
        qw.eq("reply_user_id", SysUtil.getLoginUserId(request));//回复的用户id
        qw.eq("is_read", TopicMessage.UNREAD);//查询未读
        qw.orderByDesc("create_time");//按时间降序
        List<TopicMessage> messages=this.baseMapper.selectList(qw);
        if (messages.size()==0){
            Map map = new HashMap();
            map.put("code", 1);
            return map;
        }
        TopicMessage message=messages.get(0);

        //查询信息发送人

        if (message.getType() == TopicMessage.TYPE_PROJECT_GROUP) {//项目通知
            BaseUser sys=new BaseUser();
            sys.setName("系统通知");
            message.setUser(sys);
        }else{
            BaseUser user=userService.getById(message.getUserId());
            message.setUser(user);
        }

        //查询相应话题数据
        setTopicTitle(message);
        //设置消息已读
        message.setIsRead(TopicMessage.READ);
        message.setBeRead(TopicMessage.READ);
        this.updateById(message);
//        int total = this.count(qw);
        Map map = new HashMap();
        map.put("code", 1);
//        map.put("total", total);
        map.put("data", message);
        return map;
    }
        /**
         * 设置列表状态已读
         *
         * @param topicId
         */
        @Override
        public Map<String, Object> getEdit(String topicId) {
            UpdateWrapper<TopicMessage> updateWrapper = new UpdateWrapper<>();
            updateWrapper.eq("topic_id", topicId);
            updateWrapper.set("is_read", TopicMessage.READ);
            updateWrapper.set("be_read", TopicMessage.READ);
            this.update(updateWrapper);
            return null;
        }

    /**
     * 设置消息已读
     *
     * @param topicId
     */
    private void readMessage(String topicId) {
        //将当前用户当前话题的数据设置已读

        UpdateWrapper<TopicMessage> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("topic_id", topicId);
        updateWrapper.eq("reply_user_id", SysUtil.getLoginUserId(request));
        updateWrapper.set("is_read", TopicMessage.READ);
        updateWrapper.set("be_read", TopicMessage.READ);

        this.update(updateWrapper);
    }

    @Override
    public Map<String, Object> add(TopicMessage topicMessage) {
        if (StringUtils.isEmpty(topicMessage.getTopicId())
                || StringUtils.isEmpty(topicMessage.getContent())
                || SysUtil.TARGET_TYPE_MAP.get(topicMessage.getType()) == null) {
            return ResponseInfo.error("错误的参数");
        }
        topicMessage.setId(SysUtil.UUID());//设置id
        String userId = SysUtil.getLoginUserId(request);//设置评论人
        topicMessage.setUserId(userId);
        topicMessage.setCreateTime(LocalDateTime.now());
        topicMessage.setIsRead(TopicMessage.UNREAD);
        //如果是给领导私信类型，发送人，回复人特殊处理
        if (topicMessage.getType()==TopicMessage.TYPE_LEADER){
            String topic = topicMessage.getTopicId();
            String[] ids = topic.split("-");//规格 领导id-下属id
            //如果是领导发送，回复人就是下属，否则相反
            if (userId.equals(ids[0])){
                topicMessage.setReplyUserId(ids[1]);
            }else{
                topicMessage.setReplyUserId(ids[0]);
            }
        }else{
            //其他类型，如果自己回复自己，默认已读
            if (userId.equals(topicMessage)){

            }
        }
        this.save(topicMessage);
        return ResponseInfo.success(topicMessage);
    }
    @Override
    public Map<String, Object> add2(TopicMessage topicMessage) {
        if (StringUtils.isEmpty(topicMessage.getTopicId())
                || StringUtils.isEmpty(topicMessage.getContent())
                || SysUtil.TARGET_TYPE_MAP.get(topicMessage.getType()) == null) {
            return ResponseInfo.error("错误的参数");
        }
        topicMessage.setId(SysUtil.UUID());//设置id
        String userId = SysUtil.getLoginUserId(request);//设置评论人
        topicMessage.setUserId(userId);
        topicMessage.setCreateTime(LocalDateTime.now());
        topicMessage.setIsRead(TopicMessage.UNREAD);
        //如果是给领导私信类型，发送人，回复人特殊处理
        if (topicMessage.getType()==TopicMessage.TYPE_LEADER){
            String topic = topicMessage.getTopicId();
            String[] ids = topic.split("-");//规格 领导id-下属id
            //如果是领导发送，回复人就是下属，否则相反
            if (userId.equals(ids[0])){
                topicMessage.setReplyUserId(ids[1]);
            }else{
                topicMessage.setReplyUserId(ids[0]);
            }
        }else{
            //其他类型，如果自己回复自己，默认已读
            if (userId.equals(topicMessage)){

            }
        }
        this.save(topicMessage);
        return ResponseInfo.success(topicMessage);
    }

    @Override
    public Map<String, Object> delete(String id) {
        QueryWrapper<TopicMessage> qw = new QueryWrapper<>();
        qw.eq("id", id);
        qw.or().eq("top_id", id);
        this.remove(qw);
        return ResponseInfo.success();
    }

    /**
     * 根据话题id删除数据
     *
     * @param topicId
     * @return
     */
    @Override
    public Map<String, Object> deleteByTopicId(String topicId) {
        QueryWrapper<TopicMessage> qw = new QueryWrapper<>();
        qw.eq("topic_id", topicId);
        this.remove(qw);
        return ResponseInfo.success();
    }

    @Override
    public Map<String, Object> refuse(TopicUserRefuseCount t) {
        String projectId=t.getTargetId();
        if(StringUtil.zNull(projectId).indexOf("-type-3")!=-1){
            projectId=projectId.substring(0,StringUtil.zNull(projectId).indexOf("-type-3"));
        }
        String userId=t.getUserId();
        QueryWrapper<ProjectMember> qw=new QueryWrapper<>();
        qw.eq("project_id",projectId);
        qw.eq("user_id",userId);
        List<ProjectMember> list = projectMemberService.list(qw);
        if(list.size()==1){
            ProjectMember pm = list.get(0);
            pm.setAgreeStatus(2);
            projectMemberService.updateById(pm);
        }
        //得到project_id
        t.setCreateTime(LocalDateTime.now());
        topicUserRefuseCountService.saveOrUpdate(t);
        return ResponseInfo.success();
    }

    @Override
    public Map<String, Object> agree(TopicUserRefuseCount t) {
        String projectId=t.getTargetId();
        if(StringUtil.zNull(projectId).indexOf("-type-3")!=-1){
            projectId=projectId.substring(0,StringUtil.zNull(projectId).indexOf("-type-3"));
        }
        String userId=t.getUserId();
        QueryWrapper<ProjectMember> qw=new QueryWrapper<>();
        qw.eq("project_id",projectId);
        qw.eq("user_id",userId);
        List<ProjectMember> list = projectMemberService.list(qw);
        if(list.size()==1){
            ProjectMember pm = list.get(0);
            pm.setAgreeStatus(1);
            projectMemberService.updateById(pm);
        }
        return ResponseInfo.success();
    }
}
